# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from app.forms import UserBindForm
from app.api.CamServer import LibService
from app.models import User
from app import db
from flask import render_template, Blueprint, redirect, url_for
from datetime import datetime

# 设定蓝图 index
mod = Blueprint('user', __name__)


# 处理绑定事件
@mod.route('/bind', methods=['GET', 'POST'])
def userbind():
    userform = UserBindForm()
    if userform.validate_on_submit():
        libusername = userform.libusername.data
        libpwd = userform.libpwd.data
        user = LibService(libusername, libpwd)
        if user:
            userinfo = User(
                libusername=libusername,
                libpwd=libpwd,
                username=user.REAL_NAME.split('(')[0].strip(),
                gender=user.REAL_NAME.split('(')[1][:-1],
                createtime=datetime.now(),
                bindstate=1
            )
            # 写入数据库
            db.session.add(userinfo)
            db.session.commit()
            print userinfo.username, "----"+userinfo.gender
            return redirect(url_for('.bindsuccess', gender=userinfo.gender, username=userinfo.username,libusername=userinfo.libusername))
    return render_template('/User/userbind.html', userform=userform)


# 绑定成功的提示
@mod.route('/bindsuccess/<gender>/<username>/<libusername>')
def bindsuccess(gender, username, libusername):
    return render_template('/User/bindsuccess.html', gender=gender, username=username, libusername=libusername)



